<template>
  <div class="flex flex-col h-full">
    <a-card :body-style="{ padding: '8px 12px' }">
      <a-form ref="formRef" :model="formState" class="flex justify-between">
        <div class="flex">
          <a-form-item name="zjm" class="w-[260px] mr-2 !mb-0">
            <a-input v-model:value="formState.pyjm" placeholder="床位号/姓名/助记码" />
          </a-form-item>
          <a-form-item name="dateRange" label="日期范围" class="mr-5">
            <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item class="mr-5">
            <a-radio-group v-model:value="formState.zxzt" @change="getData">
              <a-radio :value="null"> 全部 </a-radio>
              <a-radio :value="0"> 未执行 </a-radio>
              <a-radio :value="1"> 已执行 </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item class="mr-2">
            <a-radio-group v-model:value="formState.lx" @change="getData">
              <a-radio :value="null"> 全部 </a-radio>
              <a-radio :value="0"> 门诊 </a-radio>
              <a-radio :value="1"> 住院 </a-radio>
            </a-radio-group>
          </a-form-item>
        </div>

        <div>
          <a-button style="margin: 0 8px" @click="onReset">重置</a-button>
          <a-button type="primary" @click="getData">搜索</a-button>
        </div>
      </a-form>
    </a-card>
    <a-card class="mt-2 flex-1">
      <div class="flex justify-between items-center pb-4">
        <a-button type="primary" :disabled="!selectedRowKeys.length" @click="onBatchExecute"> 批量执行 </a-button>
        <!-- <a-button type="primary" disabled @click="onBatchExecute"> 批量执行 </a-button> -->
        <div>当前登录科室：{{ userStore.ksmc }}</div>
      </div>
      <BaseTable
        :loading="loading"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        column-code="000997"
        :scroll="{ x: 1600 }"
        :data-source="tableData"
        fill
      >
        <template #bodyCell="{ index, column, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'zxbz'">
            <EditCell title="执行医嘱备注">
              <SelectTags
                v-model:value="record.zxbz"
                show-setting
                show-new
                multiple
                allow-clear
                type="医嘱字典"
                :search-params="{ blcybh: '执行医嘱备注' }"
                placeholder="请输入备注"
                @blur="onChange(record)"
                @select="onChange(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'zxzt'">
            <a-tag v-if="record.zxzt === 0" color="blue">未执行</a-tag>
            <a-tag v-if="record.zxzt === 1" color="success">已执行</a-tag>
          </template>
          <template v-if="column.dataIndex === 'lx'">
            <span v-if="record.lx === 0">门诊</span>
            <span v-if="record.lx === 1">住院</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button v-if="record.zxzt == 0" type="link" size="small" @click="onExecute(record)"> 执行 </a-button>
            <template v-else>
              <ConfirmModal description="撤销执行" @confirm="onUnExecute(record)">
                <a-button danger type="text" size="small"> 撤销 </a-button>
              </ConfirmModal>
              <a-button type="link" size="small" @click="onClickExecut(record)"> 调整执行 </a-button>
            </template>
          </template>
        </template>
      </BaseTable>
      <AdjustModal v-model:open="adjustOpen" :row-data="rowData" @success="getData" />
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import useUserStore from '@/store/user'
import AdjustModal from '../components/AdjustModal'

const userStore = useUserStore()
const formRef = ref(null)
const adjustOpen = ref(false)
const rowData = ref({})
const selectedRowKeys = ref([])
const selectedRows = ref([])
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  zjm: '',
  zxzt: null,
  lx: null
})
const { loading, tableData, getData } = useTable({
  url: '/common/patient/getAdviceInfoByKeyCode',
  immediate: true,
  pagination: false,
  params: formState.value,
  formatParams: (params) => {
    return {
      ...params,
      queryStartDate: params.dateRange?.[0],
      queryEndDate: params.dateRange?.[1]
    }
  },
  onSuccess: (res) => {
    selectedRowKeys.value = res.map((i) => i.id)
    selectedRows.value = res
  }
})

// 调整执行
const onClickExecut = (row) => {
  rowData.value = { ...row }
  adjustOpen.value = true
}

const onSelectChange = (keys, rows) => {
  selectedRowKeys.value = keys
  selectedRows.value = rows
}
const onReset = () => {
  formRef.value.resetFields()
  getData()
}

const onExecute = (row) => {
  if (row.lx === 0) {
    onExecuteMz([row.id])
  } else {
    onExecuteZy([row.id], 1)
  }
}
const onUnExecute = (row) => {
  if (row.lx === 0) {
    onUnExecuteMz(row.id)
  } else {
    onExecuteZy([row.id], 0)
  }
}
const onBatchExecute = () => {
  const mzIds = selectedRows.value.filter((item) => item.lx === 0).map((item) => item.id)
  const zyIds = selectedRows.value.filter((item) => item.lx === 1).map((item) => item.id)
  if (mzIds.length) {
    onExecuteMz(mzIds)
  }
  if (zyIds.length) {
    onExecuteZy(zyIds)
  }
}
//执行门诊
const onExecuteMz = async (ids) => {
  const res = await post('/outp/mzhs/doExecuteClinicalOrder', ids)
  if (res.code !== 0) return message.error(res.msg || '执行失败')
  message.success('门诊执行成功')
  getData()
}
//撤销执行
const onUnExecuteMz = async (id) => {
  const res = await get('/outp/mzhs/doCancelExecuteClinicalOrder?yzid=' + id)
  if (res.code !== 0) return message.error(res.msg || '撤销失败')
  message.success('门诊撤销成功')
  getData()
}
//执行住院
const onExecuteZy = async (ids, type = 1) => {
  const res = await post('/inp/clinicalOrder/doNurseExecuteClinicalOrder', {
    zxyzids: ids,
    execStatus: type,
    execNurseStatus: type === 1 ? 1 : 0
  })
  if (res.code !== 0) return message.error(res.msg || '撤销失败')
  message.success('住院撤销成功')

  getData()
}
//保存执行备注
const onChange = async (row) => {
  const { code, msg } = await post('/common/patient/saveAdviceInfo', row)
  if (code !== 0) return message.error(msg || '保存失败')
  getData()
}
</script>

<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}

:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
</style>
